package com.zhongfl.crm.lixiao.batch;


import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import tech.heptagram.core.common.batch.task.AbstractTaskService;
import tech.heptagram.core.common.model.PageVo;

/**
 * 分页处理任务执行器
 */
@Slf4j
public abstract class PagingTaskService<T> extends AbstractTaskService<T> {
    public static final int DEFAULT_PAGE_INDEX = 1;
    public static final int DEFAULT_PAGE_SIZE = 100;

    private int pageIndex;
    private int pageSize;

    public PagingTaskService() {
        this(DEFAULT_PAGE_INDEX, DEFAULT_PAGE_SIZE);
    }

    public PagingTaskService(int pageIndex, int pageSize) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    /**
     * 查询任务列表
     */
    public abstract PageInfo<T> find(PageVo pageVo);

    @Override
    public void run() throws RuntimeException {
        PageVo pageVo = new PageVo();
        pageVo.setPage(this.pageIndex);
        pageVo.setPageSize(this.pageSize);

        PageInfo<T> pageInfo = find(pageVo);

        log.info("分页查询待处理任务列表, pageIndex: {} pageSize: {} resultSize: {}",
            pageVo.getPage(), pageVo.getPageSize(), pageInfo.getSize());

        while (pageInfo.getList().size() > 0) {
            processTasks(pageInfo.getList());

            pageVo.setPage(pageInfo.getNextPage());

            pageInfo = find(pageVo);
            log.info("分页查询待处理任务列表, pageIndex: {} pageSize: {} resultSize: {}",
                pageVo.getPage(), pageVo.getPageSize(), pageInfo.getSize());
        }
    }
}
